<template>
    <h3>事件处理 <a target="_blank" href="https://cn.vuejs.org/guide/essentials/event-handling.html#key-modifiers">vue 文档</a></h3>
    <input @keyup.enter="onEnter" placeholder="按下 enter 提交" />
    <input @keyup.alt.enter="onCtrlEnter" placeholder="按下ctrl + enter 提交" />

    <h3>监听器 <a target="_blank" href="https://cn.vuejs.org/guide/essentials/watchers.html#basic-example">vue 文档</a></h3>
    <p>
        <!-- v-model 绑定事件 -->
        提问(尾巴加上 `?` 表示提问完成): <input v-model="question" />
    </p>
    <p>{{ answer }}</p>
</template>

<script>
export default {
    name: "eventTemplate",
    data(){
        // 定义参数
        return {
            question: "",
            answer: ""
        }
    },
    methods: {
        onEnter(event) {
            alert("按下Enter提交, " + event.target.tagName)
        },
        onCtrlEnter(event) {
            console.log(event)
            alert("按下Ctrl + Enter提交")
        },
        async getAnswer() {
            this.answer = "我想哈...."
            try{
                const res = await fetch('https://yesno.wtf/api')
                this.answer = (await res.json()).answer
            }catch(error){
                this.answer = 'Error! 找不到答案.' + error
            }
        }
    },
    watch: {
        // 监听, 当question 改变时，调用， question 需要在data中声明
        question(newQuestion, oldQuestion) {
            if (newQuestion != oldQuestion && newQuestion.includes('?')) {
                this.getAnswer()
            }
        }
    }
}
</script>